package xdu.lz.stage1_basic.chapter2_api.d_join_interrupt_wait;

public class WaitTest extends Thread {
    private static final Object LOCK = new Object();
    @Override
    public void run(){
        synchronized (LOCK){
            System.out.println(1);
            try {
                System.out.println(2);
                LOCK.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(3);
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                synchronized (LOCK){
                    System.out.println(Thread.currentThread().getName()+" will wait");
                    try {
                        LOCK.wait();
                        System.out.println(Thread.currentThread().getName()+" be waked up");

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },"t"+i).start();
        }

        try {
            Thread.sleep(100L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                synchronized (LOCK){
                    LOCK.notify();
                    try {
                        Thread.sleep(20L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },"t"+i).start();
        }

        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        WaitTest waitTest = new WaitTest();
        waitTest.start();


        //保证线程已经被wait了，所以要延迟一下，不然可能notify才wait
        try {
            Thread.sleep(100L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        synchronized (LOCK){
            LOCK.notify();
        }
    }

}
